package com.starinside.wp.listener;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zhipu.oapi.service.v3.StandardEventSourceListener;
import lombok.Data;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Response;
import okhttp3.sse.EventSource;

/**
 * 描述：OpenAIEventSourceListener
 *
 * @author https:www.unfbx.com
 * @date 2023-02-22
 */
@Slf4j
@Data
public class GLMEventSourceListener extends StandardEventSourceListener  {


    /**
     * {@inheritDoc}
     */
    @Override
    public void onOpen(EventSource eventSource, Response response) {

        super.onOpen(eventSource, response);

    }

    /**
     * {@inheritDoc}
     */
    @SneakyThrows
    @Override
    public void onEvent(EventSource eventSource, String id, String type, String data) {
        log.info("GLM返回数据：{}", data);

        super.onEvent(eventSource, id, type, data);
        if ("finish".equals(type)) {
            log.info("GLM处理内容：{}", "[DONE]");
            return;
        }

        JSONObject jsonObject = JSON.parseObject(data);
        String curText = jsonObject.getString("data");
        log.info("GLM处理内容：{}", curText);
    }


    @Override
    public void onClosed(EventSource eventSource) {
        log.info("GLM关闭链接");
        super.onClosed(eventSource);
    }


    @SneakyThrows
    @Override
    public void onFailure(EventSource eventSource, Throwable t, Response response) {
        log.info("GLM 失败");
        t.printStackTrace();
        super.onFailure(eventSource, t, response);
    }
}
